package com.campus.help.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.campus.help.entity.Student;
import com.campus.help.mapper.StudentMapper;
import com.campus.help.service.StudentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

/**
 * 学生服务实现类
 */
@Slf4j
@Service
public class StudentServiceImpl extends ServiceImpl<StudentMapper, Student> implements StudentService {
    
    @Override
    public IPage<Student> getStudentPage(Page<Student> page, String studentId, String name, Long schoolId, String status) {
        return baseMapper.selectStudentPageWithSchool(page, studentId, name, schoolId, status);
    }
    
    @Override
    public Student getByStudentId(String studentId) {
        if (!StringUtils.hasText(studentId)) {
            return null;
        }
        return baseMapper.selectByStudentId(studentId);
    }
    
    @Override
    public boolean addStudent(Student student) {
        try {
            // 检查学号是否已存在
            Student existingStudent = getByStudentId(student.getStudentId());
            if (existingStudent != null) {
                throw new RuntimeException("学号已存在");
            }
            
            return save(student);
        } catch (Exception e) {
            log.error("添加学生失败", e);
            throw new RuntimeException("添加学生失败: " + e.getMessage());
        }
    }
    
    @Override
    public boolean updateStudent(Student student) {
        try {
            // 检查学号是否被其他学生使用
            Student existingStudent = getByStudentId(student.getStudentId());
            if (existingStudent != null && !existingStudent.getId().equals(student.getId())) {
                throw new RuntimeException("学号已被其他学生使用");
            }
            
            return updateById(student);
        } catch (Exception e) {
            log.error("更新学生失败", e);
            throw new RuntimeException("更新学生失败: " + e.getMessage());
        }
    }
    
    @Override
    public boolean deleteStudent(Long id) {
        try {
            return removeById(id);
        } catch (Exception e) {
            log.error("删除学生失败", e);
            throw new RuntimeException("删除学生失败: " + e.getMessage());
        }
    }
    
    @Override
    public boolean updateStudentStatus(Long id, String status) {
        try {
            return baseMapper.updateStatus(id, status) > 0;
        } catch (Exception e) {
            log.error("更新学生状态失败", e);
            throw new RuntimeException("更新学生状态失败: " + e.getMessage());
        }
    }
}